import { MongoClient, Db, Collection } from 'mongodb';
import { env } from '../../config';
class db2 {
    private client: MongoClient;
    private db!: Db;
    private url: string = env.mongodb_url;

    constructor() {
        this.client = new MongoClient(this.url);
    }

    async connect() {
        console.log(`开始连接数据库:${this.url}`);
        try {
            await this.client.connect();
            console.log(`连接数据库成功:${this.url}`);
            this.db = this.client.db(env.mongodb_db); // Set the database name here
            // console.log('Connected to MongoDB');
            // await this.insert('test', { name: 'John', age: 30 }); // Ensure this is awaited
            // let a = await this.update('test', { name: 'John' }, {  name: '999', age: 99 })
            // console.log(a)
            // debugger;
            // this.update('test',{name:'666'},{name:'666',test:111})
        } catch (error) {
            console.log(`连接数据库失败:${this.url}`);
        }
    }
    // 添加一个随机获取方法
    async findRandom(collectionName: string, query: any = {}) {
        const result = await this.db.collection(collectionName).aggregate([
            { $match: query },
            { $sample: { size: 1 } }
        ]).toArray();
        return result[0];
    }
    getCollection(collectionName: string): Collection {
        return this.db.collection(collectionName);
    }

    async insert(collectionName: string, document: any) {
        const collection = this.getCollection(collectionName);
        const result = await collection.insertOne(document);
        return result.insertedId;
    }

    async find(collectionName: string, query?: any) {
        const collection = this.getCollection(collectionName);
        const documents = await collection.find(query || {}).toArray();
        return documents;
    }

    async update(collectionName: string, query: any, update: any) {
        const collection = this.getCollection(collectionName);
        const result = await collection.updateOne(query, { $set: update }, { upsert: true });
        return result.modifiedCount || result.upsertedCount;
    }

    async remove(collectionName: string, query: any) {
        const collection = this.getCollection(collectionName);
        const result = await collection.deleteOne(query);
        return result.deletedCount;
    }
}

export default new db2();